package lv.solcraft.replication.server.rest.restlets;

import java.util.Arrays;

import lv.solcraft.replication.server.api.UpdateOperStatesCommand;
import lv.solcraft.replication.server.model.OperId;
import lv.solcraft.replication.server.model.OperState;
import lv.solcraft.replication.server.model.OperStateUpdate;

import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Resource;
import org.restlet.resource.Variant;

public class MoveOperSiteResource extends Resource {

    private OperId operId;
    private UpdateOperStatesCommand updateOperStatesCommand;
    private OperState newState;
    private long siteId;

    public void setUpdateOperStatesCommand(UpdateOperStatesCommand updateOperStatesCommand) {
        this.updateOperStatesCommand = updateOperStatesCommand;
    }

    @Override
    public void init(Context context, Request request, Response response) {
        super.init(context, request, response);
        siteId = Long.parseLong(request.getAttributes().get("site").toString());
        newState = OperState.valueOf(request.getAttributes().get("newState").toString());
        long originSiteId = Long.parseLong(request.getAttributes().get("originSiteId").toString());
        long originOperId = Long.parseLong(request.getAttributes().get("originOperId").toString());
        operId = new OperId(originSiteId, originOperId);
        getVariants().add(new Variant(MediaType.TEXT_PLAIN));
    }

    @Override
    public boolean allowPost() {
        return true;
    }

    @Override
    public void handlePost() {
        OperStateUpdate update = new OperStateUpdate(siteId, operId, newState, "Manual");
        updateOperStatesCommand.updateStates(Arrays.asList(update));
    }
}
